package com.culture.bootdemo.common.exception;

import com.culture.bootdemo.common.basevo.Result;
import com.culture.bootdemo.common.basevo.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author wen
 * @date Created in 2019/9/19
 * @Description: 方法较为简单，返回异常未作细分处理： 详细见GlobalExceptionHandler类
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        log.error("handleException:", e);
        return new Result(ResultCode.ERROR);
    }


    /**
     * 404NotFound
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handleNoHandlerFoundException(NoHandlerFoundException e) {
        log.error("handleNoHandlerFoundException:", e);
        return new Result(ResultCode.NOT_FOUND);
    }

    /**
     * 参数校验: 用于识别 @NotNull @NotBlank等注解
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(), ex);
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        List<String> errors = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList());
        return new Result(ResultCode.REQUEST_PARAM_VALIDATION_ERROR.getCode(), errors.toString());
    }
}
